<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<div class="card">
    <div class="card-header">
        <h4 class="mb-0">用户管理</h4>
    </div>
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-hover">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>用户名</th>
                        <th>邮箱</th>
                        <th>答题次数</th>
                        <th>正确率</th>
                        <th>注册时间</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody id="userList">
                    <!-- 用户列表将通过JavaScript动态加载 -->
                </tbody>
            </table>
        </div>
        <nav aria-label="Page navigation">
            <ul class="pagination justify-content-center" id="pagination">
                <!-- 分页将通过JavaScript动态加载 -->
            </ul>
        </nav>
    </div>
</div>

<script>
$(document).ready(function() {
    var currentPage = 1;
    var pageSize = 10;

    // 获取角色标签
    function getRoleBadge(role) {
        switch(role) {
            case 'ADMIN': return '<span class="badge bg-danger">管理员</span>';
            case 'USER': return '<span class="badge bg-success">普通用户</span>';
            default: return '<span class="badge bg-secondary">未知</span>';
        }
    }

    // 加载用户列表
    function loadUsers(page) {
        $.get('${pageContext.request.contextPath}/admin/user/api/list', {
            page: page,
            size: pageSize
        }, function(response) {
            if (response.code === 200) {
                var users = response.data.list;
                var total = response.data.total;
                var html = '';

                users.forEach(function(user) {
                    html += '<tr>';
                    html += '<td>' + user.id + '</td>';
                    html += '<td>' + user.username + '</td>';
                    html += '<td>' + (user.email || '-') + '</td>';
                    html += '<td>' + user.answerCount + '</td>';
                    html += '<td>' + (user.accuracy || '0') + '%</td>';
                    html += '<td>' + utils.formatDate(user.createdAt) + '</td>';
                    html += '<td>';
                    if (user.id != ${sessionScope.user.id}) {  // 不能删除自己
                        html += '<button class="btn btn-sm btn-danger" onclick="deleteUser(' + user.id + ')">删除</button>';
                    }
                    html += '</td>';
                    html += '</tr>';
                });

                $('#userList').html(html);
                updatePagination(page, Math.ceil(total / pageSize));
            }
        });
    }

    // 更新分页
    function updatePagination(currentPage, totalPages) {
        var html = '';
        
        // 上一页
        html += '<li class="page-item ' + (currentPage <= 1 ? 'disabled' : '') + '">';
        html += '<a class="page-link" href="#" data-page="' + (currentPage - 1) + '" aria-label="Previous">';
        html += '<span aria-hidden="true">&laquo;</span></a></li>';
        
        // 页码
        for (var i = 1; i <= totalPages; i++) {
            if (i === currentPage) {
                html += '<li class="page-item active"><span class="page-link">' + i + '</span></li>';
            } else {
                html += '<li class="page-item"><a class="page-link" href="#" data-page="' + i + '">' + i + '</a></li>';
            }
        }
        
        // 下一页
        html += '<li class="page-item ' + (currentPage >= totalPages ? 'disabled' : '') + '">';
        html += '<a class="page-link" href="#" data-page="' + (currentPage + 1) + '" aria-label="Next">';
        html += '<span aria-hidden="true">&raquo;</span></a></li>';
        
        $('#pagination').html(html);
    }

    // 切换用户角色
    window.toggleRole = function(id, currentRole) {
        var newRole = currentRole === 'ADMIN' ? 'USER' : 'ADMIN';
        if (confirm('确定要将该用户角色改为' + (newRole === 'ADMIN' ? '管理员' : '普通用户') + '吗？')) {
            $.ajax({
                url: '${pageContext.request.contextPath}/admin/user/api/role/' + id,
                type: 'PUT',
                data: { role: newRole },
                success: function(response) {
                    if (response.code === 200) {
                        loadUsers(currentPage);
                    } else {
                        alert(response.message);
                    }
                }
            });
        }
    };

    // 删除用户
    window.deleteUser = function(id) {
        if (confirm('确定要删除这个用户吗？')) {
            $.ajax({
                url: '${pageContext.request.contextPath}/admin/user/api/delete/' + id,
                type: 'DELETE',
                success: function(response) {
                    if (response.code === 200) {
                        loadUsers(currentPage);
                    } else {
                        alert(response.message);
                    }
                }
            });
        }
    };

    // 绑定分页点击事件
    $(document).on('click', '.pagination .page-link', function(e) {
        e.preventDefault();
        var page = $(this).data('page');
        if (page > 0) {
            currentPage = page;
            loadUsers(currentPage);
        }
    });

    // 初始化
    loadUsers(currentPage);
});
</script>
